package cn.imvc.app.models;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.domains.ActivityType;
import cn.imvc.app.domains.AppResult;
import cn.imvc.app.domains.CartItemInfo;
import cn.imvc.app.domains.Constants;
import cn.imvc.app.domains.FundFlowType;
import cn.imvc.app.domains.GenerateOrderInfo;
import cn.imvc.app.domains.GoodsState;
import cn.imvc.app.domains.OrderState;
import cn.imvc.app.domains.OrderType;
import cn.imvc.app.domains.StorageOrderInfo;
import cn.imvc.app.entities.Activity;
import cn.imvc.app.entities.Address;
import cn.imvc.app.entities.Area;
import cn.imvc.app.entities.Cart;
import cn.imvc.app.entities.Express;
import cn.imvc.app.entities.ExpressFee;
import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.GoodsOrder;
import cn.imvc.app.entities.GoodsSku;
import cn.imvc.app.entities.Member;
import cn.imvc.app.entities.Orders;
import cn.imvc.app.entities.Seller;
import cn.imvc.app.entities.Storage;
import cn.imvc.app.entities.StorageOrder;
import cn.imvc.app.entities.Voucher;
import cn.imvc.app.repositories.AddressRepository;
import cn.imvc.app.repositories.CartRepository;
import cn.imvc.app.repositories.ExpressFeeRepository;
import cn.imvc.app.repositories.ExpressRepository;
import cn.imvc.app.repositories.GoodsOrderRepository;
import cn.imvc.app.repositories.GoodsSkuRepository;
import cn.imvc.app.repositories.OrdersRepository;
import cn.imvc.app.repositories.SellerRepository;
import cn.imvc.app.repositories.StorageOrderRepository;
import cn.imvc.service.api.GoodsService;
import cn.imvc.util.RandomId;

@Service
public class OrderModelImpl implements OrderModel {
	@Autowired
	private AddressRepository addressRepository;
	@Autowired
	private CartRepository cartRepository;
	@Autowired
	private SellerRepository sellerRepository;
	@Autowired
	private OrdersRepository ordersRepository;
	@Autowired
	private StorageOrderRepository storageOrderRepository;
	@Autowired
	private GoodsOrderRepository goodsOrderRepository;
	@Autowired
	private ExpressRepository expressRepository;
	@Autowired
	private ExpressFeeRepository expressFeeRepository;
	@Autowired
	private GoodsSkuRepository goodsSkuRepository;
	@Autowired
	private CartModel cartModel;
	@Autowired
	private StorageOrderModel storageOrderModel;
	@Autowired
	private GoodsOrderModel goodsOrderModel;
	@Autowired
	private FundFlowModel fundFlowModel;
	@Autowired
	private AccountModel accountModel;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ActivityModel activityModel;
	@Autowired
	private VoucherModel voucherModel;
	@Autowired
	private MemberModel memberModel;
	
	@Autowired
	private SystemConfig systemConfig;
	
	/**
	 * 免运费额度
	 */
	@Value("${freight.freeLimit}")
	private Integer freeFreightLimit;

	
	@Override
	public Map<String, Object> updateCartsAndshowPreOrderInfo(Member member, String cookieCartItemsStr, Integer addressId, boolean singleBuyFlag) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// List<Cart> dbCarts =
		// cartRepository.findByMemberIdAndIsBuy(member.getId(), (byte) 1);
		List<Cart> dbCarts = cartRepository.findByMemberId(member.getId());
		Map<String, Cart> cartItemWithskuIdKey = new HashMap<String, Cart>();
		for (Cart cart2 : dbCarts) {
			cartItemWithskuIdKey.put("skuId" + cart2.getSku().getId(), cart2);
		}
		if (cookieCartItemsStr.endsWith(".")) {
			cookieCartItemsStr = cookieCartItemsStr.substring(0, cookieCartItemsStr.length() - 1);
		}
		if (StringUtils.isEmpty(cookieCartItemsStr)) {
			return resultMap;
		}
		String[] cartItems = cookieCartItemsStr.split("\\.");
		List<Cart> toBuyCarts = new ArrayList<Cart>();
		// cartId-skuId-num-isBuy-isDel
		for (String item : cartItems) {
			String[] temInfo = item.split("-");
			Cart cart = null;
			if (!"1".equals(temInfo[4]) && "1".equals(temInfo[3])) {// 如果不是删除且为选中购买
				cart = cartItemWithskuIdKey.get("skuId" + temInfo[1]);
				if (cart == null) {//
					cart = cartModel.bulidCartItem(null, Integer.valueOf(temInfo[1]), Integer.valueOf(temInfo[2]), member, true);
				}
				if (cart != null) {
					cart.setGoodsNum(Integer.valueOf(temInfo[2]));
					toBuyCarts.add(cart);
				}
			}
		}
		Assert.notEmpty(toBuyCarts);
		// default address
		// Address address = addressRepository.findByMemberAndIsDefault(member,
		// (byte) 1);
		Address address = null;
		if (addressId != null) {
			address = addressRepository.getOne(addressId);
		} else {
			address = addressRepository.findByMemberAndIsDefault(member, (byte) 1);
		}
		Map<String, List<Cart>> cartItemsGroupByStorageId = toBuyCarts.stream()
				.collect(Collectors.groupingBy(cart -> "storage" + cart.getGoods().getStorage().getId()));
		// Map<String, Object> result = new HashMap<String, Object>();
		resultMap.put("address", address);
		resultMap.put("cartItemsGroupByStorageId", cartItemsGroupByStorageId);
		// 每个仓库查询快递
		IntStream ids = cartItemsGroupByStorageId.keySet().stream().mapToInt((id) -> Integer.valueOf(id.replace("storage", "")));
		StringBuffer idsStr = new StringBuffer();
		ids.forEach((id) -> idsStr.append(id + ","));
		idsStr.deleteCharAt(idsStr.length() - 1);
		String expressSql = "select st.id storageId,e.id,e.code,e.name FROM `express` e,seller s,`storage`  st where st.sellerId=s.id and e.sellerId=s.id and st.id in ("
				+ idsStr + ") and e.state = 1";
		List<Object[]> expressList = expressRepository.findAllSql(expressSql);
		Map<String, List<Object[]>> expressGroupByStorageId = expressList.stream().collect(Collectors.groupingBy(express -> "storageExpress" + express[0]));
		resultMap.put("expressGroupByStorageId", expressGroupByStorageId);
		if (!singleBuyFlag) {// 单个购买不需要同步
			// 此处做一次同步，因为上一步是可以修改购物项信息的。（删除或者修改数量）
			Map<String, Object> synchronizedResult = cartModel.updateAndListCartItems(member, cookieCartItemsStr);
			resultMap.put("synchronizeCookieStr", synchronizedResult.get("synchronizeCookieStr"));
		}
		int goodsAmount = toBuyCarts.stream().filter(item -> item.getSku().getState() != GoodsState.GIFT_STATE.getCode())
				.mapToInt(item -> item.getGoodsNum() * item.getGoodsPrice()).sum();
		// 优惠活动
		List<Object[]> activityInfoList = activityModel.getActivitiesInfoByOrderAmount(goodsAmount);
		resultMap.put("activityInfoList", activityInfoList);
		// 代金券
		List<Voucher> voucherList = voucherModel.getVouchersInfoByOrderAmount(member.getId(), goodsAmount, (byte) 0, new Date());
		resultMap.put("voucherList", voucherList);
		//不需要地址的快递code
		resultMap.put("noneedExpressCode", Constants.NONEED_ADDRESS_EXPRESS_CODE);
		return resultMap;
	}

	@Override
	public Map<String, Object> saveGeneratedOrders(Member member, GenerateOrderInfo orderInfo) {
		// 订单信息不能为空
		Assert.notEmpty(orderInfo.getStorageOrderInfoList());
		Map<String, Object> result = new HashMap<>();
		// List<Cart> dbCarts =
		// cartRepository.findByMemberIdAndIsBuy(member.getId(), (byte) 1);
		List<Cart> dbCarts = cartRepository.findByMemberId(member.getId());
		Map<String, Object> formatedStruct = getFormatedStruct(dbCarts, orderInfo, member,true);
		List<Cart> toBuyCarts = (List<Cart>) formatedStruct.get("toBuyCarts");
		Map<String, Cart> cartItemWithskuIdKey = (Map<String, Cart>) formatedStruct.get("cartItemWithskuIdKey");
		Map<String, List<Cart>> cartItemsWithStorageIdKey = (Map<String, List<Cart>>) formatedStruct.get("cartItemsWithStorageIdKey");
		Address address = addressRepository.findOne(orderInfo.getAddressId());
		// 一级订单
		Orders order = bulidOrders(member, toBuyCarts, orderInfo, address,false);
		ordersRepository.save(order);
		// 更新代金券使用情况
		Object o = formatedStruct.get("voucher");
		if (o != null) {
			Voucher voucher = (Voucher) o;
			voucher.setOrder(order);
			voucher.setOrderCode(order.getCode());
			// 已用
			voucher.setState((byte) 1);
			voucherModel.save(voucher);
		}
		// 二级订单
		List<StorageOrder> storageOrders = bulidStorageOrders(member, orderInfo, address, order, cartItemsWithStorageIdKey,false);
		storageOrderRepository.save(storageOrders);
		// 三级订单
		List<GoodsOrder> goodsOrders = bulidGoodsOrders(member, toBuyCarts, order, storageOrders, false);
		goodsOrderRepository.save(goodsOrders);
		// 删除购物车选项
		for (Cart cart : toBuyCarts) {
			if (cart.getId() != 0) {
				cartRepository.delete(cart);
			}
		}
		// 更新本地购物车cookie，前台需要同步
		List<Cart> carts = cartRepository.findByMemberId(member.getId());
		// 生成新串
		String synchronizeCookieStr = cartModel.generateCookieStrByCarts(carts);
		result.put("synchronizeCookieStr", synchronizeCookieStr);
		result.put("orderInfo", order);
		// 更新库存
		// goodsService.retryBatchUpdateGoodsInventory(getUpdateInventorySkuInfos(orderInfo.getStorageOrderInfoList()),true);
		goodsService.retryBatchUpdateGoodsInventory(getUpdateInventoryInfos(goodsOrders), true);
		return result;
	}

	private List<Integer[]> getUpdateInventoryInfos(List<GoodsOrder> goodsOrders) {
		List<Integer[]> skuInfos = new ArrayList<Integer[]>();
		goodsOrders.forEach((item) -> skuInfos.add(new Integer[] { item.getGoodsSku().getId(), item.getNum(), item.getId() }));
		return skuInfos;
	}

	private List<Integer[]> getUpdateInventorySkuInfos(List<StorageOrderInfo> storageOrderInfoList) {
		List<Integer[]> skuInfos = new ArrayList<Integer[]>();
		storageOrderInfoList.forEach((item) -> {
			List<CartItemInfo> carts = item.getCarts();
			carts.forEach((cart) -> skuInfos.add(new Integer[] { cart.getSkuId(), cart.getNum() }));
		});
		return skuInfos;
	}

	/**
	 * 获取格式化后的数据结构
	 * 
	 * @param dbCarts
	 * @param orderInfo
	 * @param member
	 * @param giftCheck
	 * @return
	 */
	private Map<String, Object> getFormatedStruct(List<Cart> dbCarts, GenerateOrderInfo orderInfo, Member member,boolean giftCheck) {
		if(orderInfo.getAddressId()==null||orderInfo.getAddressId()==0){//如果地址是空，那么所有的快递都是自提。否则异常
			int[] expressIds = orderInfo.getStorageOrderInfoList().stream().mapToInt(storageOrderInfo->storageOrderInfo.getExpressId()).toArray();
			List<Express>  expressList = expressRepository.findByIdIn(expressIds);
			for (Express express : expressList) {
				if(Constants.NONEED_ADDRESS_EXPRESS_CODE.indexOf(express.getCode())==-1){//如果不是自提
					throw new RuntimeException("非自提快递，收货地址不能为空！");
				}
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		List<Cart> toBuyCarts = new ArrayList<Cart>();
		Map<String, Cart> cartItemWithskuIdKey = new HashMap<String, Cart>();
		Map<String, List<Cart>> cartItemsWithStorageIdKey = new HashMap<String, List<Cart>>();
		if (dbCarts != null && dbCarts.size() > 0) {
			for (Cart cart2 : dbCarts) {
				cartItemWithskuIdKey.put("skuId" + cart2.getSku().getId(), cart2);
			}
		}
		for (StorageOrderInfo storageOrderInfo : orderInfo.getStorageOrderInfoList()) {
			List<CartItemInfo> carts = storageOrderInfo.getCarts();
			Integer storageId = storageOrderInfo.getStorageId();
			// Integer expressId = storageOrderInfo.getExpressId();
			List<Cart> storageCarts = cartItemsWithStorageIdKey.get("storageId" + storageId);
			if (storageCarts == null) {
				storageCarts = new ArrayList<Cart>();
				cartItemsWithStorageIdKey.put("storageId" + storageId, storageCarts);
			}
			for (CartItemInfo cartItemInfo : carts) {
				Integer skuId = cartItemInfo.getSkuId();
				Integer num = cartItemInfo.getNum();
				Cart cart = cartItemWithskuIdKey.get("skuId" + skuId);
				if (cart == null) {
					cart = cartModel.bulidCartItem(null, skuId, num, member, giftCheck);
					Assert.notNull(cart, "item can't find!");// TODO 构建新对象还是抛出异常
				} else {
					if (cart.getGoodsNum() != num)// 如果数量和数据库数量不一致，统一为页面数量
						cart.setGoodsNum(num);
				}
				toBuyCarts.add(cart);
				storageCarts.add(cart);
			}
		}
		result.put("toBuyCarts", toBuyCarts);
		result.put("cartItemWithskuIdKey", cartItemWithskuIdKey);
		result.put("cartItemsWithStorageIdKey", cartItemsWithStorageIdKey);
		int goodsAmount = toBuyCarts.stream().mapToInt((item) -> item.getGoodsPrice() * item.getGoodsNum()).sum();
		handelActivityInfo(orderInfo, result, member, goodsAmount);
		handelVoucherInfo(orderInfo, goodsAmount, result);
		return result;
	}

	/**
	 * 处理优惠券信息
	 * 
	 * @param orderInfo
	 * @param orderAmount
	 */
	private void handelVoucherInfo(GenerateOrderInfo orderInfo, int orderAmount, Map<String, Object> result) {
		// TODO 优惠券信息
		Integer voucherId = orderInfo.getVoucherId();
		if (voucherId == null || voucherId == 0) {// 没有活动信息
			return;
		}
		Voucher voucher = voucherModel.checkIsValid(orderAmount, voucherId);
		if (voucher != null) {// 有效
			voucher.getPrice();
			orderInfo.setDiscountAmount(voucher.getPrice() + orderInfo.getDiscountAmount());
			result.put("voucher", voucher);
		}
	}

	/**
	 * 处理活动信息
	 * 
	 * @param orderInfo
	 * @param result
	 * @param member
	 * @param orderAmount
	 */
	private void handelActivityInfo(GenerateOrderInfo orderInfo, Map<String, Object> result, Member member, int orderAmount) {
		// 获取赠品信息 赠品信息处理方式 ：分别添加到商品对应仓库订单中tobuycarts。 这种方式适用范围很受限
		Integer activityId = orderInfo.getActivityId();
		if (activityId == null || activityId == 0) {
			return;
		}
		Activity activity = activityModel.getOne(activityId);
		if (activity == null) {
			return;
		}
		// 活动类型
		Byte activityType = activity.getType();
		List<Cart> toBuyCarts = (List<Cart>) result.get("toBuyCarts");
		boolean isValid = activityModel.checkIsValid(orderAmount, activityId);
		if (!isValid) {// TODO 前台传来的活动信息不可用
			return;
		}
		if (activityType == ActivityType.LARGESS.getCode()) {// 满赠
			// check 活动是否适用该订单，skuid是否在该活动范围内
			Integer giftSkuId = orderInfo.getGiftSkuId();
			if (giftSkuId != null && giftSkuId != 0) {
				String skuIds = activity.getSkuId();
				if (skuIds != null) {
					String[] skuIdArr = skuIds.split(",");
					boolean isInclude = false;
					for (int i = 0; i < skuIdArr.length; i++) {
						if (String.valueOf(giftSkuId).equals(skuIdArr[i])) {
							isInclude = true;
							break;
						}
					}
					if (!isInclude) {// 该skuId不在活动范围内
						return;// TODO
					}
				}
				GoodsSku goodsSku = goodsSkuRepository.findOne(giftSkuId);
				Assert.isTrue(goodsSku.getState() == GoodsState.GIFT_STATE.getCode(), "商品状态不为赠品！");
				Map<String, List<Cart>> cartItemsWithStorageIdKey = (Map<String, List<Cart>>) result.get("cartItemsWithStorageIdKey");
				Cart cart = cartModel.bulidCartItem(null, goodsSku.getId(), 1, member, false);
				Integer storageId = goodsSku.getGoods().getStorage().getId();
				// 判断是否在已有仓库
				List<StorageOrderInfo> storageOrderInfoList = orderInfo.getStorageOrderInfoList();
				// 构建对象
				CartItemInfo cartItem = new CartItemInfo();
				cartItem.setSkuId(giftSkuId);
				cartItem.setNum(1);
				// 取商品所在的仓库
				Object[] arr = storageOrderInfoList.stream().filter(item -> item.getStorageId() == storageId).toArray();
				List<Cart> storageCarts = cartItemsWithStorageIdKey.get("storageId" + storageId);
				if (storageCarts == null) {// 赠品不在已有仓库
					StorageOrderInfo newStorageOrderInfo = new StorageOrderInfo();
					newStorageOrderInfo.setStorageId(storageId);
					String expressSql = "select st.id storageId,e.* FROM `express` e,seller s,`storage`  st where st.sellerId=s.id and e.sellerId=s.id and st.id = "
							+ storageId + " and e.state = 1 and e.isDefault = 1";
					List<Object[]> expressList = expressRepository.findAllSql(expressSql);
					Integer expressId = (Integer) expressList.get(0)[1];
					newStorageOrderInfo.setExpressId(expressId);
					List<CartItemInfo> carts = new ArrayList<>();
					carts.add(cartItem);
					newStorageOrderInfo.setCarts(carts);
					//
					storageOrderInfoList.add(newStorageOrderInfo);
					storageCarts = new ArrayList<>();
					cartItemsWithStorageIdKey.put("storageId" + storageId, storageCarts);
				} else {// 添加进已有仓库
					StorageOrderInfo storageOrderInfo = (StorageOrderInfo) arr[0];
					storageOrderInfo.getCarts().add(cartItem);
				}
				storageCarts.add(cart);
				toBuyCarts.add(cart);
			}
		} else if (activityType == ActivityType.DISCOUNT.getCode()) {// 满减
			// 记录满减金额
			orderInfo.setDiscountAmount(activity.getDiscountMoney() + orderInfo.getDiscountAmount());
		}
	}

	/**
	 * 构造商品(三级)订单
	 * 
	 * @param member
	 * @param cartItems
	 * @param order
	 * @param storageOrders
	 * @param pointBuy
	 *            是否积分消费
	 * 
	 * @return
	 */
	private List<GoodsOrder> bulidGoodsOrders(Member member, List<Cart> cartItems, Orders order, List<StorageOrder> storageOrders,
			boolean pointBuy) {
		Map<String, StorageOrder> storageOrderWithStorageIdKey = new HashMap<String, StorageOrder>();
		for (StorageOrder storageOrder : storageOrders) {
			storageOrderWithStorageIdKey.put("storage" + storageOrder.getStorage().getId(), storageOrder);
		}
		List<GoodsOrder> goodsOrders = new ArrayList<GoodsOrder>();
		for (Cart cartItem : cartItems) {
			GoodsOrder goodsOrder = new GoodsOrder();
			Goods goods = cartItem.getGoods();
			GoodsSku goodsSku = cartItem.getSku();
			goodsOrder.setCode(OrderType.Goods.getValue() + RandomId.randomId(new Date().getTime()));
			goodsOrder.setCreatedAt(new Date());
			goodsOrder.setDetail(goods.getDetail());
			goodsOrder.setFreightState(goods.getIsFreight());
			goodsOrder.setGoods(goods);
			goodsOrder.setGoodsSku(cartItem.getSku());
			goodsOrder.setImage(goods.getImage());
			// TODO
			goodsOrder.setIsSevenDaysReturned((byte) 1);
			goodsOrder.setIsVirtual(goods.getIsVirtual());
			goodsOrder.setMember(member);
			goodsOrder.setName(goods.getName());
			goodsOrder.setNum(cartItem.getGoodsNum());
			goodsOrder.setOrder(order);
			goodsOrder.setOrderCode(order.getCode());
			// StorageOrder selected = (StorageOrder)
			// storageOrders.stream().filter((storage) ->
			// goods.getStorage().getId() ==
			// storage.getStorage().getId()).toArray()[0];
			StorageOrder selected = storageOrderWithStorageIdKey.get("storage" + goods.getStorage().getId());
			goodsOrder.setOrderStorage(selected);
			goodsOrder.setOrderStorageCode(selected.getCode());
			int point = 0;
			//byte orderState = OrderState.Create.getValue();
			byte orderState = order.getState();
			if (pointBuy) {// 如果是积分消费，字段存储为负值
				point = -(cartItem.getSku().getPoints());
				orderState = OrderState.PaySuccess.getValue();
			} else if (goods.getState() == GoodsState.GIFT_STATE.getCode()) {// 赠品  设为0
				point = 0;
			} else {// 正常商品
				point = cartItem.getGoodsPrice() / 100;
			}
			goodsOrder.setPoints(point);
			goodsOrder.setPrice(cartItem.getGoodsPrice());
			goodsOrder.setSeller(selected.getSeller());
			goodsOrder.setSpec(goodsSku.getSpecName());
			goodsOrder.setState(orderState);
			goodsOrder.setStorage(selected.getStorage());
			goodsOrder.setTitle(goods.getTitle());
			goodsOrder.setTotals(cartItem.getGoodsNum() * cartItem.getGoodsPrice());
			goodsOrder.setWeight(goodsSku.getWeight());
			// TODO added at 2016/09/14 赠品 是否有必要使用枚举类
			goodsOrder.setIsFree(goodsSku.getState() == GoodsState.GIFT_STATE.getCode() ? (byte) 1 : (byte) 0);
			goodsOrders.add(goodsOrder);
		}
		return goodsOrders;
	}

	/**
	 * 构造仓库(二级)订单
	 * 
	 * @param member
	 * @param cartItems
	 * @param address
	 * @param order
	 * @param pointBuy
	 *            积分消费
	 * @return
	 */
	private List<StorageOrder> bulidStorageOrders(Member member, GenerateOrderInfo orderInfo, Address address, Orders order,
			Map<String, List<Cart>> cartItemsWithStorageIdKey, boolean pointBuy) {
		List<StorageOrder> storageOrders = new ArrayList<StorageOrder>();
		List<StorageOrderInfo> storageOrderInfoList = orderInfo.getStorageOrderInfoList();
		for (StorageOrderInfo storageOrderInfo : storageOrderInfoList) {
			StorageOrder storageOrder = new StorageOrder();
			storageOrder.setCode(OrderType.Storage.getValue() + RandomId.randomId(new Date().getTime()));
			storageOrder.setCreatedAt(new Date());
			List<Cart> carts = cartItemsWithStorageIdKey.get("storageId" + storageOrderInfo.getStorageId());
			// TODO 优惠金额
			int discountAmount = carts.stream().filter(cart -> cart.getSku().getState() == GoodsState.GIFT_STATE.getCode())
					.mapToInt(item -> item.getGoodsPrice() * item.getGoodsNum()).sum();
			storageOrder.setDiscountAmount(discountAmount);
			Storage storage = new Storage();
			storage.setId(storageOrderInfo.getStorageId());
			storageOrder.setStorage(storage);
			// 分销商
			Seller seller = sellerRepository.findByStorageId(storageOrderInfo.getStorageId());
			storageOrder.setSeller(seller);
			Express express = expressRepository.findOne(storageOrderInfo.getExpressId());
			storageOrder.setExpress(express);
			// TODO 是否需要重新根据用户等级查询一次
			int goodsAmount = carts.stream().mapToInt(item -> item.getGoodsPrice() * item.getGoodsNum()).sum();
			storageOrder.setGoodsAmount(goodsAmount);
			Integer[] expressFees = calculateFreightAmount(orderInfo, address, storageOrderInfo.getStorageId(), null,goodsAmount-discountAmount);
			storageOrder.setFreight(expressFees[2]);
			storageOrder.setMember(member);
			// storageOrder.setIsDelayed();
			storageOrder.setOverweightFreight(expressFees[1]);
			// 商品费用+运费-优惠
			storageOrder.setResultAmount(goodsAmount + expressFees[2] - discountAmount);
			// 重量
			storageOrder.setWeight(expressFees[3]);
			storageOrder.setOrder(order);
			storageOrder.setOrderCode(order.getCode());
			//byte orderState = OrderState.Create.getValue();
			byte orderState = order.getState();
			if(pointBuy){//如果是积分消费，生成订单时设置为支付成功状态
				orderState = OrderState.PaySuccess.getValue();
			}
			storageOrder.setState(orderState);
			storageOrder.setRemark(storageOrderInfo.getRemark());
			storageOrders.add(storageOrder);
		}
		return storageOrders;
	}

	/**
	 * 构造总(一级)订单
	 * 
	 * @param member
	 * @param cartItems
	 * @param generateOrderInfo
	 * @param address
	 * @return
	 */
	private Orders bulidOrders(Member member, List<Cart> cartItems, GenerateOrderInfo generateOrderInfo, Address address,boolean pointBuy) {
		Orders order = new Orders();
		order.setMember(member);
		// 拼接省市县
		if(address!=null){
			StringBuffer addressSb = new StringBuffer();
			StringBuffer addressIdSb = new StringBuffer();
			addressSb.append(address.getProvince() != null ? address.getProvince().getName() : "");
			addressSb.append((address.getCity() != null && !"其他".equals(address.getCity().getName())) ? address.getCity().getName() : "");
			addressSb.append((address.getCounty() != null && !"其他".equals(address.getCounty().getName())) ? address.getCounty().getName() : "");
			addressIdSb.append((address.getProvince() != null ? address.getProvince().getId() : "") + ",");
			addressIdSb.append((address.getCity() != null ? address.getCity().getId() : "") + ",");
			addressIdSb.append((address.getCounty() != null ? address.getCounty().getId() : ""));
			order.setAddressId(addressIdSb.toString());
			order.setAddress(addressSb.append(" " + address.getAddress()).toString());
			order.setTelephone(address.getMobPhone());
			order.setName(address.getName());
		}
		// 生成订单号
		order.setCode(OrderType.Order.getValue() + RandomId.randomId(new Date().getTime()));
		order.setCreatedAt(new Date());

		// TODO 优惠金额
		int discountAmount = cartItems.stream().filter(cart -> cart.getSku().getState() == GoodsState.GIFT_STATE.getCode())
				.mapToInt(item -> item.getGoodsPrice() * item.getGoodsNum()).sum();
		int goodsAmount = cartItems.stream().mapToInt((item) -> item.getGoodsPrice() * item.getGoodsNum()).sum();
		// 计算总金额
		order.setGoodsAmount(goodsAmount);
		//非赠品商品总总额
		int noGiftGoodsAmount = goodsAmount - discountAmount;
		// 满赠商品的金额+（优惠券的金额和满减金额）
		discountAmount += generateOrderInfo.getDiscountAmount();
		order.setDiscountAmount(discountAmount);
		// 计算运费
		if(address!=null){
//			List<GoodsSku> goodsSkuList = new ArrayList<>();
//			cartItems.stream().forEach((i) -> goodsSkuList.add(i.getSku()));
			// Assert.isTrue(cartItems.size() == goodsSkuList.size(), "size must be
			// equal");
//			Integer weightAmount = goodsSkuList.stream().filter(sku -> sku.getGoods().getIsFreight() != null && sku.getGoods().getIsFreight() == 1)
//					.mapToInt((sku) -> sku.getWeight() == null ? 0 : sku.getWeight()).sum();
			Integer weightAmount = cartItems.stream().filter(cart -> cart.getGoods().getIsFreight()!= null && cart.getGoods().getIsFreight() != 1)
					.mapToInt(item -> item.getSku().getWeight() * item.getGoodsNum()).sum();
			//订单金额
			order.setFreightAmount(calculateFreightAmount(generateOrderInfo, address, null, weightAmount,noGiftGoodsAmount)[2]);
		}else{
			order.setFreightAmount(0);
		}
		// 商品金额加上其它费用
		order.setOrderAmount(goodsAmount + order.getFreightAmount());
		if(order.getOrderAmount() - order.getDiscountAmount()<0){//优惠金额大于订单应付金额
			order.setDiscountAmount(order.getOrderAmount());
		}
		// 应付金额
		order.setResultAmount(order.getOrderAmount() - order.getDiscountAmount());
		if(pointBuy){
			order.setState(OrderState.PaySuccess.getValue());
		}else{
			if(order.getResultAmount()==0){//如果应付金额为0
				order.setState(OrderState.PaySuccess.getValue());
			}else{
				order.setState(OrderState.Create.getValue());
			}
		}
		return order;
	}

	/**
	 * 计算运费
	 * 
	 * @param generateOrderInfo
	 * @param address
	 * @param storageId
	 *            若不为null，则计算该仓库运费；否则计算所有仓库运费并返回最大值
	 * @param orderWeight
	 *            订单有效重量
	 * @param noGiftGoodsAmout
	 *            非赠品订单商品金额
	 * @return Integer[首重运费,超重运费,总运费,总重量]
	 */
	private Integer[] calculateFreightAmount(GenerateOrderInfo generateOrderInfo, Address address, Integer storageId, Integer orderWeight,Integer noGiftGoodsAmout) {
		if(noGiftGoodsAmout==null){
			noGiftGoodsAmout = 0;
		}
		Integer[] result = new Integer[4];
		Integer freightAmount = 0;
		Integer weightAmount = 0;
		List<StorageOrderInfo> storageOrderInfoList = generateOrderInfo.getStorageOrderInfoList();
		Assert.notEmpty(storageOrderInfoList);
		StorageOrderInfo storageOrderInfo = null;
		if (storageId != null) {// 单个仓库订单运费
			List<StorageOrderInfo> tem = storageOrderInfoList.stream().filter((singleItem) -> singleItem.getStorageId() == storageId)
					.collect(Collectors.toList());
			if (tem != null && tem.size() == 1) {
				storageOrderInfo = tem.get(0);
				Assert.notNull(storageOrderInfo, "storageOrderInfo can't be null!");
				result = doCalculate(storageOrderInfo, address, orderWeight);
				if(noGiftGoodsAmout>=freeFreightLimit){//如果订单满设定金额，免运费
					result[2] = 0;
				}
				return result;
			}
		}
		for (StorageOrderInfo temStorageOrderInfo : storageOrderInfoList) {
			Integer[] temResult = doCalculate(temStorageOrderInfo, address, orderWeight);
			Integer temFreightAmount = temResult[2];
			Integer temWeightAmount = temResult[3];
			weightAmount += temWeightAmount;
			freightAmount = temFreightAmount > freightAmount ? temFreightAmount : freightAmount;
		}
		if(noGiftGoodsAmout>=freeFreightLimit){//如果订单满设定金额，免运费
			result[2] = 0;
		}else{
			result[2] = freightAmount;
		}
		result[3] = weightAmount;
		return result;
	}

	private Integer[] doCalculate(StorageOrderInfo storageOrderInfo, Address address, Integer orderWeight) {
		Integer[] result = new Integer[4];
		// 运费 先查询 express_fee 若无对应记录则查询express
		Integer expressId = storageOrderInfo.getExpressId();
		Express express = expressRepository.findOne(expressId);
		ExpressFee expressFee = null;
		// List<Integer> areaIds = new ArrayList<Integer>();
		if(address!=null){
			Area country = address.getCounty();
			if (country != null && expressFee == null) {
				expressFee = expressFeeRepository.findByExpressAndAreaId(express, country.getId());
				// areaIds.add(country.getId());
			}
			Area city = address.getCity();
			if (city != null && expressFee == null) {
				expressFee = expressFeeRepository.findByExpressAndAreaId(express, city.getId());
				// areaIds.add(city.getId());
			}
			Area province = address.getProvince();
			if (province != null && expressFee == null) {
				// areaIds.add(province.getId());
				expressFee = expressFeeRepository.findByExpressAndAreaId(express, province.getId());
			}
		}
		// ExpressFee expressFee =
		// expressFeeRepository.findByExpressAndAreaIdIn(express, areaIds);
		Integer first = express.getFirst();
		Integer firstPrice = express.getFirstPrice();
		Integer ad = express.getAdditional();
		Integer adPrice = express.getAdditionalPrice();
		if (expressFee != null) {// 有值，按此计算运费
			first = expressFee.getFirst();
			firstPrice = expressFee.getFirstPrice();
			ad = expressFee.getAdditional();
			adPrice = expressFee.getAdditionalPrice();
		} else {// 按express计算
		}
		List<CartItemInfo> cartItemInfo = storageOrderInfo.getCarts();
		Map<String,Integer> skuNumInfos = new HashMap<>();
		for (CartItemInfo item : cartItemInfo) {
			skuNumInfos.put("skuId"+item.getSkuId(), item.getNum());
		}
		List<GoodsSku> goodsSkuList = goodsSkuRepository.findByIdIn(cartItemInfo.stream().mapToInt((i) -> i.getSkuId()).toArray());
		Assert.isTrue(cartItemInfo.size() == goodsSkuList.size(), "size must be equal");
		// Integer weightAmount = goodsSkuList.stream().mapToInt((sku) ->
		// sku.getWeight() == null ? 0 : sku.getWeight()).sum();
		Integer orderGoodsWithoutGiftSize = goodsSkuList.stream().filter(sku -> sku.getGoods().getIsFreight() != null && sku.getGoods().getIsFreight() == 1)
				.toArray().length;
		Integer weightAmount = goodsSkuList.stream().filter(sku -> sku.getGoods().getIsFreight() != null && sku.getGoods().getIsFreight() == 1)
				.mapToInt((sku) -> sku.getWeight() == null ? 0 : sku.getWeight()*skuNumInfos.get("skuId"+sku.getId())).sum();
		if (orderWeight == null) {
			orderWeight = weightAmount;
		}
		Integer additionalCost = 0;
		if (orderWeight > first) {
			if(ad == 0){
				additionalCost = 0;
			}else{
				additionalCost = ((orderWeight - first) + ad - 1) / ad * adPrice;
			}
		}
		result[0] = firstPrice;
		result[1] = additionalCost;
		if (orderGoodsWithoutGiftSize == 0) {// 如果单子只有一个免运费的商品
			result[2] = 0;
		} else {
			result[2] = firstPrice + additionalCost;
		}
		result[3] = weightAmount;
		return result;
	}

	public Orders findByCode(String code) {
		return ordersRepository.findByCode(code);
	}

	public Orders save(Orders orders) {
		return ordersRepository.saveAndFlush(orders);
	}

	public Orders get(int id) {
		return ordersRepository.findOne(id);
	}

	public void finishPay(String code, String payCode, Date payTime) {

		Orders orders = findByCode(code);
		if (orders.getState() != OrderState.Payment.getValue()) {
			return;
		}
		orders.setPayTime(payTime);
		orders.setPayCode(payCode);
		orders.setState(OrderState.PaySuccess.getValue());
		orders.setUpdatedAt(new Date());
		save(orders);
		// 是否全部都是自提
		Boolean isAllZiti = true;

		Set<StorageOrder> storageOrders = orders.getStorageOrder();
		for (StorageOrder storageOrder : storageOrders) {
			Byte state = 0;
			// 是否自提
			if ("ZITI".equals(storageOrder.getExpress().getCode())) {
				state = OrderState.Delivered.getValue();
				storageOrder.setDeliveryTime(new Date());
				Calendar calendar = new GregorianCalendar(); 
				calendar.setTime(new Date());
				calendar.add(calendar.DATE, systemConfig.getReceiptEndOfDays());
				storageOrder.setReceiptEndTime(calendar.getTime());
			} else {
				isAllZiti = false;
				state = OrderState.PaySuccess.getValue();
			}
			storageOrder.setState(state);
			storageOrder.setUpdatedAt(new Date());
			storageOrderModel.save(storageOrder);
			Set<GoodsOrder> goodsOrders = storageOrder.getGoodsOrder();
			for (GoodsOrder goodsOrder : goodsOrders) {
				goodsOrder.setState(state);
				goodsOrder.setUpdatedAt(new Date());
				goodsOrderModel.save(goodsOrder);
			}
		}
		// 全部自提就将1级订单改为待发货
		if (isAllZiti) {
			orders.setState(OrderState.Delivery.getValue());
			orders.setUpdatedAt(new Date());
			save(orders);
		}
		fundFlowModel.addFundFlow(orders.getMember(), -orders.getResultAmount(), code, FundFlowType.Buy.getValue(), orders.getMember());
	}

	public Page<Orders> findByState(Byte state, Integer memberId, PageRequest pageRequest) {

		return ordersRepository.findByState((byte) state, state == 0, memberId, pageRequest);
	}

	public Page<Orders> findByStateTwoLevel(Byte state, Member member, PageRequest pageRequest) {
		if (member.getDealer().getDealerLevel().getType()==0){
			return ordersRepository.findByStateOneLevel((byte) state, state == 0, member.getId(), pageRequest);
		}
		if (member.getDealer().getDealerLevel().getType()==2){
			return ordersRepository.findByStateAllLevel((byte) state, state == 0, member.getGuid(), pageRequest);
		}
		String str=getMemberStr(member).toString();
		if (str.length()<1){
			return ordersRepository.findByStateOneLevel((byte) 100, false, member.getId(), pageRequest);
		}
		str=str.substring(1);
		List<Integer> memberIds=new ArrayList<Integer>();
		String[] strs=str.split(",");
		for(String tmp:strs){
			memberIds.add(Integer.parseInt(tmp));
		}
		return ordersRepository.findByStateSomeLevel((byte) state, state == 0, memberIds,  pageRequest);
	}
	
	public StringBuffer getMemberStr(Member member) {
		StringBuffer str = new StringBuffer();
		List<Member> memberList = memberModel.findByParent(member);
		for (Member tmpMember : memberList) {
			str.append("," + tmpMember.getId());
			if (tmpMember.getDealer().getDealerLevel().getType() != 1) {
				str.append(getMemberStr(tmpMember));
			}
		}
		return str;
	}

	public AppResult cancelOrder(Member member, Integer orderId) {
		AppResult result = new AppResult();
		Orders order = get(orderId);
		if (order == null) {
			result.setCode("0");
			result.setMsg("订单为空");
			return result;
		}
		if (order.getMember().getId() != member.getId()) {
			result.setCode("0");
			result.setMsg("您没有权限这么做");
			return result;
		}
		if (order.getState() != OrderState.Create.getValue() && order.getState() != OrderState.Payment.getValue()) {
			result.setCode("0");
			result.setMsg("该订单不能被取消");
			return result;
		}
		order.setState(OrderState.UserCancel.getValue());
		order.setCancelTime(new Date());
		order.setUpdatedAt(new Date());
		save(order);
		List<Integer[]> skuInfos = new ArrayList<Integer[]>();
		Set<StorageOrder> storageOrders = order.getStorageOrder();
		for (StorageOrder storageOrder : storageOrders) {
			storageOrder.setState(OrderState.UserCancel.getValue());
			storageOrder.setUpdatedAt(new Date());
			storageOrderRepository.save(storageOrder);
			Set<GoodsOrder> goodsOrders = storageOrder.getGoodsOrder();
			for (GoodsOrder goodsOrder : goodsOrders) {
				goodsOrder.setState(OrderState.UserCancel.getValue());
				goodsOrder.setUpdatedAt(new Date());
				goodsOrderRepository.save(goodsOrder);
				skuInfos.add(new Integer[] { goodsOrder.getGoodsSku().getId(), -goodsOrder.getNum() });
			}
		}
		goodsService.retryBatchUpdateGoodsInventory(skuInfos, false);
		result.setCode("1");
		result.setMsg("取消成功");
		return result;
	}

	public AppResult cancelPayOrder(Member member, Integer orderId) {
		AppResult result = new AppResult();
		Orders order = get(orderId);
		if (order == null) {
			result.setCode("0");
			result.setMsg("订单为空");
			return result;
		}
		if (order.getMember().getId() != member.getId()) {
			result.setCode("0");
			result.setMsg("您没有权限这么做");
			return result;
		}
		if (order.getState() != OrderState.PaySuccess.getValue()) {
			result.setCode("0");
			result.setMsg("该订单不能被取消");
			return result;
		}
		Set<StorageOrder> storageOrders = order.getStorageOrder();
		for (StorageOrder storageOrder : storageOrders) {
			if (storageOrder.getState() != OrderState.PaySuccess.getValue()) {
				result.setCode("0");
				result.setMsg("该订单不能被取消");
				return result;
			}
			Set<GoodsOrder> goodsOrders = storageOrder.getGoodsOrder();
			for (GoodsOrder goodsOrder : goodsOrders) {
				if (goodsOrder.getState() != OrderState.PaySuccess.getValue()) {
					result.setCode("0");
					result.setMsg("该订单不能被取消");
					return result;
				}
			}
		}
		order.setState(OrderState.PayCancel.getValue());
		order.setCancelTime(new Date());
		order.setUpdatedAt(new Date());
		save(order);
		storageOrders = order.getStorageOrder();
		List<Integer[]> skuInfos = new ArrayList<Integer[]>();

		Integer points = 0;

		for (StorageOrder storageOrder : storageOrders) {
			storageOrder.setState(OrderState.PayCancel.getValue());
			storageOrder.setUpdatedAt(new Date());
			storageOrderRepository.save(storageOrder);
			Set<GoodsOrder> goodsOrders = storageOrder.getGoodsOrder();
			for (GoodsOrder goodsOrder : goodsOrders) {
				if (goodsOrder.getPoints() < 0) {
					points = points - goodsOrder.getPoints()*goodsOrder.getNum();
				}
				goodsOrder.setState(OrderState.PayCancel.getValue());
				goodsOrder.setUpdatedAt(new Date());
				goodsOrderRepository.save(goodsOrder);
				skuInfos.add(new Integer[] { goodsOrder.getGoodsSku().getId(), -goodsOrder.getNum() });
			}
		}
		fundFlowModel.addFundFlow(member, order.getResultAmount(), order.getCode(), FundFlowType.Refund.getValue(), member);
		fundFlowModel.addFundFlow(member, points, order.getCode(), FundFlowType.PointsUp.getValue(), member);
		goodsService.retryBatchUpdateGoodsInventory(skuInfos, false);
		accountModel.retrySaveAccount(member.getAccount().getId(), order.getResultAmount(), 0, points);
		result.setCode("1");
		result.setMsg("取消成功");
		return result;
	}

	public AppResult receiptStorageOrder(Member member, Integer orderId) {
		AppResult result = new AppResult();
		StorageOrder storageOrder = storageOrderRepository.getOne(orderId);
		if (storageOrder == null) {
			result.setCode("0");
			result.setMsg("订单为空");
			return result;
		}
		if (storageOrder.getMember().getId() != member.getId()) {
			result.setCode("0");
			result.setMsg("您没有权限这么做");
			return result;
		}
		if (storageOrder.getState() != OrderState.Delivered.getValue()) {
			result.setCode("0");
			result.setMsg("该订单不能确认收货");
			return result;
		}

		storageOrder.setState(OrderState.Receipt.getValue());
		storageOrder.setReceiptTime(new Date());
		storageOrder.setUpdatedAt(new Date());
		storageOrderRepository.save(storageOrder);
		Set<GoodsOrder> goodsOrders = storageOrder.getGoodsOrder();
		for (GoodsOrder goodsOrder : goodsOrders) {
			if (goodsOrder.getState() == OrderState.Delivered.getValue()) {
				goodsOrder.setState(OrderState.Receipt.getValue());
				goodsOrder.setUpdatedAt(new Date());
				goodsOrderRepository.save(goodsOrder);
			}
		}
		result.setCode("1");
		result.setMsg("确认收货成功");
		return result;
	}

	public StorageOrder getStorageOrder(Integer storageOrderId) {
		return storageOrderRepository.findOne(storageOrderId);
	}

	public Map<String, Object> pointsBuyPreOrderInfo(Member member, String cookieCartItemsStr, Integer addressId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (cookieCartItemsStr.endsWith(".")) {
			cookieCartItemsStr = cookieCartItemsStr.substring(0, cookieCartItemsStr.length() - 1);
		}
		if (StringUtils.isEmpty(cookieCartItemsStr)) {
			return resultMap;
		}
		String[] cartItems = cookieCartItemsStr.split("\\.");
		List<Cart> toBuyCarts = new ArrayList<Cart>();
		// cartId-skuId-num-isBuy-isDel
		for (String item : cartItems) {
			String[] temInfo = item.split("-");
			Cart cart = null;
			if (!"1".equals(temInfo[4]) && "1".equals(temInfo[3])) {// 如果不是删除且为选中购买
				cart = cartModel.bulidCartItem(null, Integer.valueOf(temInfo[1]), Integer.valueOf(temInfo[2]), member, false);
				toBuyCarts.add(cart);
			}
		}
		Assert.notEmpty(toBuyCarts);
		Address address = null;
		if (addressId != null) {
			address = addressRepository.getOne(addressId);
		} else {
			address = addressRepository.findByMemberAndIsDefault(member, (byte) 1);
		}
		Map<String, List<Cart>> cartItemsGroupByStorageId = toBuyCarts.stream()
				.collect(Collectors.groupingBy(cart -> "storage" + cart.getGoods().getStorage().getId()));
		// Map<String, Object> result = new HashMap<String, Object>();
		resultMap.put("address", address);
		resultMap.put("cartItemsGroupByStorageId", cartItemsGroupByStorageId);
		// 每个仓库查询快递
		IntStream ids = cartItemsGroupByStorageId.keySet().stream().mapToInt((id) -> Integer.valueOf(id.replace("storage", "")));
		StringBuffer idsStr = new StringBuffer();
		ids.forEach((id) -> idsStr.append(id + ","));
		idsStr.deleteCharAt(idsStr.length() - 1);
		String expressSql = "select st.id storageId,e.id,e.code,e.name FROM `express` e,seller s,`storage`  st where st.sellerId=s.id and e.sellerId=s.id and st.id in ("
				+ idsStr + ") and e.state = 1";
		List<Object[]> expressList = expressRepository.findAllSql(expressSql);
		Map<String, List<Object[]>> expressGroupByStorageId = expressList.stream().collect(Collectors.groupingBy(express -> "storageExpress" + express[0]));
		resultMap.put("expressGroupByStorageId", expressGroupByStorageId);
		resultMap.put("pointBuyFlag", "1");
		int userPoints = memberModel.get(member.getId()).getAccount().getPoints();
		resultMap.put("userPoints", userPoints);
		//不需要地址的快递code
		resultMap.put("noneedExpressCode", Constants.NONEED_ADDRESS_EXPRESS_CODE);
		return resultMap;
	}

	public Map<String, Object> savePointsBuy(Member member, GenerateOrderInfo orderInfo) {
		// 订单信息不能为空
		Assert.notEmpty(orderInfo.getStorageOrderInfoList());
		Map<String, Object> result = new HashMap<>();
		Map<String, Object> formatedStruct = getFormatedStruct(null, orderInfo, member,false);
		List<Cart> toBuyCarts = (List<Cart>) formatedStruct.get("toBuyCarts");
		Map<String, Cart> cartItemWithskuIdKey = (Map<String, Cart>) formatedStruct.get("cartItemWithskuIdKey");
		Map<String, List<Cart>> cartItemsWithStorageIdKey = (Map<String, List<Cart>>) formatedStruct.get("cartItemsWithStorageIdKey");
		Address address = addressRepository.findOne(orderInfo.getAddressId());
		// 一级订单
		Orders order = bulidOrders(member, toBuyCarts, orderInfo, address,true);
		ordersRepository.save(order);
		// 二级订单
		List<StorageOrder> storageOrders = bulidStorageOrders(member, orderInfo, address, order, cartItemsWithStorageIdKey,true);
		storageOrderRepository.save(storageOrders);
		// 三级订单
		List<GoodsOrder> goodsOrders = bulidGoodsOrders(member, toBuyCarts, order, storageOrders, true);
		goodsOrderRepository.save(goodsOrders);
		//负值积分
		int userPoints = memberModel.get(member.getId()).getAccount().getPoints();
		int pointSum = goodsOrders.stream().mapToInt(goodsOrder->goodsOrder.getPoints()*goodsOrder.getNum()).sum();
		Assert.isTrue(userPoints+pointSum>0,"积分不足！");
		//修改积分
		accountModel.retrySaveAccount(member.getAccount().getId(), order.getResultAmount(), 0, pointSum);
		//记录积分消费
		fundFlowModel.addFundFlow(member, pointSum, order.getCode(), FundFlowType.PointsDown.getValue(), member);
		
		// 删除购物车选项
//		for (Cart cart : toBuyCarts) {
//			if (cart.getId() != 0) {
//				cartRepository.delete(cart);
//			}
//		}
		// 更新本地购物车cookie，前台需要同步
		List<Cart> carts = cartRepository.findByMemberId(member.getId());
		// 生成新串
		String synchronizeCookieStr = cartModel.generateCookieStrByCarts(carts);
		result.put("synchronizeCookieStr", synchronizeCookieStr);
		result.put("orderInfo", order);
		// 更新库存
		// goodsService.retryBatchUpdateGoodsInventory(getUpdateInventorySkuInfos(orderInfo.getStorageOrderInfoList()),true);
		goodsService.retryBatchUpdateGoodsInventory(getUpdateInventoryInfos(goodsOrders), true);
		result.put("pointsConsumeResult", "true");
		return result;
	}
}
